package com.example.demo.modules.customDefine.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.util.R;
import com.example.demo.modules.customDefine.entity.FieldType;
import com.example.demo.modules.customDefine.service.FieldTypeService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

import static com.example.demo.common.util.Utils.isNil;


@RestController
@RequestMapping("/api/fieldType")
public class FieldTypeController {

    @Autowired
    private FieldTypeService fieldTypeService;


    @GetMapping("/listAll")
    public R listAll() {
        return R.ok().put("result", fieldTypeService.list(null));
    }

    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", dataType = "String")
    })
    public R page(
            Integer pageSize, Integer pageNum) {
        if (isNil(pageSize)) {
            pageSize = 10;
        }
        if (isNil(pageNum)) {
            pageNum = 0;
        }
        QueryWrapper<FieldType> queryWrapper = new QueryWrapper<>();
        return R.ok().put("result", fieldTypeService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @PostMapping("/add")
    public R add(@RequestBody FieldType fieldType) {
        if (null == fieldType.getDescription() || "".equals(fieldType.getDescription())) {
            return R.error().put("msg", "getDescription is required");
        }
        return R.ok().put("result", fieldTypeService.save(fieldType));
    }

    @PostMapping("/update")
    public R update(@RequestBody FieldType fieldType, HashMap<String, Object> updateOptions) {
        QueryWrapper<FieldType> queryWrapper = new QueryWrapper<>();
        if (!isNil(fieldType.getId())) {
            queryWrapper.eq("id", fieldType.getId());
        } else {
            return R.error("id不能为空");
        }
        return R.ok().put("result", fieldTypeService.update(fieldType, queryWrapper));
    }

    @GetMapping("/delete")
    public R deleteOne(@RequestParam(value = "id", required = true) String id) {
        return R.ok().put("result", fieldTypeService.removeById(Convert.toInt(id)));
    }

}
